package org.credo.socket.thread;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

public class MyServer {

	//定义保存所有的Socket的ArrayList
	public static ArrayList<Socket> socketList=new ArrayList<>();
	
	@SuppressWarnings("resource")
	public static void main(String[] args) throws IOException {
		ServerSocket ss=new ServerSocket(30000);
		while(true){
			//this line of code has been block,waiting for the connection
			Socket s=ss.accept();
			socketList.add(s);
			//new thread for this client
			new Thread(new ServerThread(s)).start();
		}
	}

}

class ServerThread implements Runnable{
	
	//define current process thread
	Socket s=null;
	//this thread process's socket's inputStream
	BufferedReader br=null;
	
	public ServerThread(Socket socket) throws IOException{
		this.s=socket;
		//init this socket's inputStream
		br=new BufferedReader(new InputStreamReader(s.getInputStream()));
	}
	
	@Override
	public void run() {
		System.out.println("ininin");
		String content=null;
		while((content=readFromClient())!=null){
			//foreach all socket,and send.
			for(Socket s:MyServer.socketList){
				PrintStream ps;
				try {
					ps = new PrintStream(s.getOutputStream());
					ps.print(content);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	private String readFromClient(){
		try {
			return br.readLine();
		} catch (IOException e) {
			MyServer.socketList.remove(s);
			e.printStackTrace();
		}
		return null;
	}
	
}